<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <div>
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ getTitle.value }} </span>
      </template>
      <template #toolbar>
        <!-- <a-button type="primary" @click="handleFormWh({})" v-auth="'wh:pd:whPdStock:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('按仓库盘点') }}
        </a-button> -->
        <!-- <a-button type="primary" @click="handleForm({})" v-auth="'wh:pd:whPdStock:edit'">
          <Icon icon="i-fluent:add-12-filled" /> {{ t('新增') }}
        </a-button> -->
        <a-button type="default" @click="handleExport()">
          <Icon icon="i-ant-design:download-outlined" /> {{ t('导出') }}
        </a-button>
        <!-- 
        <a-button type="default" @click="handleImport()">
          <Icon icon="i-ant-design:upload-outlined" /> {{ t('导入') }}
        </a-button> -->
        <a-button type="default" @click="handleSyn({})" v-auth="'wh:pd:whPdStock:edit'">
          <Icon icon="i-simple-line-icons:refresh" /> {{ t('同步') }}
        </a-button>
        <Popconfirm placement="bottom" :title="t('是否确认撤销？')" @confirm="handleCancel">
          <a-button type="default" v-auth="'wh:pd:whPdStock:edit'">
            <Icon icon="ant-design:code-outlined" /> {{ t('撤销') }}
          </a-button>
        </Popconfirm>
        <Popconfirm placement="bottom" :title="t('是否推送？')" @confirm="handlets">
          <a-button type="default" v-auth="'wh:pd:whPdStock:edit'">
            <Icon icon="ant-design:check-outlined" /> {{ t('推送') }}
          </a-button>
        </Popconfirm>
        <Popconfirm placement="bottom" :title="t('是否生成盘点单？')" @confirm="handleGenerateTask">
          <a-button type="dashed" success v-auth="'wh:pd:whPdStock:edit'">
            <Icon icon="i-ant-design:check-outlined" /> {{ t('生成盘点单') }}
          </a-button>
        </Popconfirm>
      </template>
      <template #firstColumn="{ record }">
        <a @click="handleForm({ id: record.id, isView: true })">
          {{ record.fbillno }}
        </a>
      </template>
    </BasicTable>
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <InputFormWh @register="registerDrawerWh" @success="handleSuccessWh" />
  </div>
</template>
<script lang="ts" setup name="ViewsWmsWhPdList">
  import { unref, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { Popconfirm } from 'ant-design-vue';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import {
    whPdStockDelete,
    whPdStockListData,
    synPdStock,
    pushK3PdData,
    calBackk3PdData,
  } from '/@/api/wms/wh/pd/whPdStock';
  import { createStockBill, overPdBill } from '/@/api/wms/wh/pd/whPdStockBill';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import { useGlobSetting } from '/@/hooks/setting';
  import { downloadByUrl } from '/@/utils/file/download';
  import InputForm from './form.vue';
  import InputFormWh from './formWh.vue';
  import { companyTreeData } from '/@/api/sys/company';
  import { useUserStore } from '/@/store/modules/user';

  const userStore = useUserStore();

  const { t } = useI18n('wh.pd.whPdStock');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);

  const getTitle = {
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: meta.title || t('盘点单管理'),
  };

  const searchForm: FormProps = {
    baseColProps: { lg: 6, md: 8 },
    labelWidth: 90,
    schemas: [
      // {
      //   label: t('公司编码'),
      //   field: 'companyCode',
      //   component: 'Input',
      // },
      {
        label: t('公司'),
        field: 'companyCode',
        fieldLabel: 'companyName',
        component: 'TreeSelect',
        componentProps: {
          api: companyTreeData,
          allowClear: true,
          immediate: true,
          onChange: handleSuccess,
        },
      },
      // {
      //   label: t('公司名称'),
      //   field: 'companyName',
      //   component: 'Input',
      // },
      {
        label: t('单据日期'),
        field: 'fdate',
        component: 'RangePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
          // showTime: { format: 'HH:mm' },
        },
      },
      {
        label: t('单据号'),
        field: 'fbillno',
        component: 'Input',
      },
      {
        label: t('单据状态'),
        field: 'djStatus',
        component: 'Select',
        componentProps: {
          dictType: 'wms_pd_status',
          allowClear: true,
        },
      },
      // {
      //   label: t('备注'),
      //   field: 'fexplanation',
      //   component: 'Input',
      // },
      // {
      //   label: t('总数'),
      //   field: 'iqty',
      //   component: 'Input',
      // },
      // {
      //   label: t('实盘总数'),
      //   field: 'sumqty',
      //   component: 'Input',
      // },
      {
        label: t('是否推送'),
        field: 'bsend',
        component: 'Select',
        componentProps: {
          dictType: 'sys_yes_no',
          allowClear: true,
        },
      },
      {
        label: t('推送时间'),
        field: 'senddate',
        component: 'RangePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
        },
      },
      // {
      //   label: t('状态'),
      //   field: 'status',
      //   component: 'Select',
      //   componentProps: {
      //     dictType: 'sys_search_status',
      //     allowClear: true,
      //     onChange: handleSuccess,
      //   },
      // },
      {
        label: t('制单人'),
        field: 'fbiller',
        component: 'Input',
      },
      {
        label: t('备注'),
        field: 'fexplanation',
        component: 'Input',
      },
    ],
    fieldMapToTime: [
      ['senddate', ['senddate_gte', 'senddate_lte']],
      ['fdate', ['fdate_gte', 'fdate_lte']],
    ],
  };
  const tableColumns: BasicColumn[] = [
    {
      title: t('公司名称'),
      dataIndex: 'companyName',
      key: 'a.company_name',
      sorter: true,
      width: 230,
      align: 'left',
    },
    {
      title: t('单据号'),
      dataIndex: 'fbillno',
      key: 'a.fbillno',
      sorter: true,
      width: 130,
      align: 'left',
      slot: 'firstColumn',
    },
    {
      title: t('单据日期'),
      dataIndex: 'fdate',
      key: 'a.fdate',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('单据状态'),
      dataIndex: 'djStatus',
      key: 'a.dj_status',
      sorter: true,
      width: 130,
      align: 'left',
      dictType: 'wms_pd_status',
    },
    {
      title: t('总数'),
      dataIndex: 'iqty',
      key: 'a.iqty',
      sorter: true,
      width: 100,
      align: 'right',
      showSummary: true,
    },
    {
      title: t('实盘总数'),
      dataIndex: 'sumqty',
      key: 'a.sumqty',
      sorter: true,
      width: 100,
      align: 'right',
      showSummary: true,
    },

    {
      title: t('是否推送'),
      dataIndex: 'bsend',
      key: 'a.bsend',
      sorter: true,
      width: 130,
      align: 'left',
      dictType: 'sys_yes_no',
    },
    {
      title: t('推送时间'),
      dataIndex: 'senddate',
      key: 'a.senddate',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('盘点方式'),
      dataIndex: 'pdType',
      key: 'a.pdType',
      sorter: true,
      width: 100,
      align: 'left',
      dictType: 'wms_pd_type',
    },
    {
      title: t('仓库'),
      dataIndex: 'basWare.cwhname',
      key: 'a.whcode',
      sorter: true,
      width: 100,
      align: 'left',
    },
    // {
    //   title: t('公司编码'),
    //   dataIndex: 'companyCode',
    //   key: 'a.company_code',
    //   sorter: true,
    //   width: 130,
    //   align: 'left',
    // },
    
    // {
    //   title: t('状态'),
    //   dataIndex: 'status',
    //   key: 'a.status',
    //   sorter: true,
    //   width: 130,
    //   align: 'center',
    //   dictType: 'sys_search_status',
    // },
    {
      title: t('修改时间'),
      dataIndex: 'updateDate',
      key: 'a.update_date',
      sorter: true,
      width: 130,
      align: 'center',
    },
    // {
    //   title: t('备注'),
    //   dataIndex: 'remarks',
    //   key: 'a.remarks',
    //   sorter: true,
    //   width: 130,
    //   align: 'left',
    // },
    {
      title: t('制单人'),
      dataIndex: 'fbiller',
      key: 'a.fbiller',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('备注'),
      dataIndex: 'fexplanation',
      key: 'a.fexplanation',
      sorter: true,
      width: 130,
      align: 'left',
    },
  ];

  const actionColumn: BasicColumn = {
    width: 160,
    actions: (record: Recordable) => [
      {
        icon: 'i-clarity:note-edit-line',
        title: t('编辑盘点单'),
        onClick: handleForm.bind(this, { id: record.id }),
        auth: 'wh:pd:whPdStock:edit',
        ifShow: () => {
          return record.sourceFlag !== '0';
        },
      },
      {
        icon: 'i-ant-design:delete-outlined',
        color: 'error',
        title: t('删除盘点单'),
        popConfirm: {
          title: t('是否确认删除盘点单'),
          confirm: handleDelete.bind(this, record),
        },
        auth: 'wh:pd:whPdStock:edit',
        ifShow: () => {
          return record.sourceFlag !== '0';
        },
      },
    ],
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawerWh, { openDrawer: openDrawerWh }] = useDrawer();
  const [registerTable, { reload, getSelectRowKeys, getSelectRows, getForm, setLoading, setProps }] = useTable({
    api: whPdStockListData,
    beforeFetch: (params) => {
      return params;
    },
    columns: tableColumns,
    // actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    showCustomSummary: true,
    rowKey: 'fbillno',
    rowSelection: {
      type: 'checkbox',
    },
  });

  function handleForm(record: Recordable, isView?: boolean) {
    openDrawer(true, record, isView);
  }

  function handleFormWh(record: Recordable, isView?: boolean) {
    openDrawerWh(true, record, isView);
  }

  async function handleDelete(record: Recordable) {
    try {
      setLoading(true);
      const params = { id: record.id };
      const res = await whPdStockDelete(params);
      showMessage(res.message);
      handleSuccess(record);
    } catch (error) {
      console.error('删除操作失败:', error);
      showMessage('删除操作失败，请重试');
    } finally {
      setLoading(false);
    }
  }

  function handleSuccess(record: Recordable) {
    reload({ record });
  }

  // 同步
  async function handleSyn() {
    try {
      setLoading(true);
      const res = await synPdStock({});
      showMessage(res.message);
      handleSuccess({});
    } catch (error) {
      console.error('同步操作失败:', error);
      // showMessage('同步操作失败，请重试');
    } finally {
      setLoading(false);
    }
  }

  async function handleGenerateTask() {
    let arr = getSelectRowKeys();
    if (getSelectRowKeys().length != 1) {
      showMessage(t('请选择一行数据'));
      return;
    }

    try {
      setLoading(true);
      const selIds = arr.join(',');
      const params = { sourceNo: selIds };
      const res = await createStockBill(params);
      console.log(res, 'res');
      showMessage(res.message || '生成任务成功');
      handleSuccess({});
    } catch (error) {
      console.error('生成任务失败:', error);
    } finally {
      setLoading(false);
    }
  }

  async function handlets() {
    if (getSelectRowKeys().length) {
      try {
        setLoading(true);
        let selIds = getSelectRowKeys().join(',');
        const res = await pushK3PdData({ selIds });
        showMessage(res.message);
        handleSuccess({});
      } catch (error) {
        console.error('推送操作失败:', error);
        showMessage('推送操作失败，请重试');
      } finally {
        setLoading(false);
      }
    } else {
      showMessage('请先选择数据');
    }
  }

  async function handleCancel() {
    if (getSelectRowKeys().length == 1) {
      try {
        // 开启 loading
        setLoading(true);
        const res = await calBackk3PdData({ fbillno: getSelectRowKeys()[0] });
        showMessage(res.message);
        handleSuccess({});
      } catch (error) {
        console.error('撤销操作失败:', error);
        showMessage('撤销操作失败，请重试');
      } finally {
        // 关闭 loading
        setLoading(false);
      }
    } else {
      showMessage('请先选择一条数据');
    }
  }

  async function handleExport() {
    const { ctxAdminPath } = useGlobSetting();
    downloadByUrl({
      url: ctxAdminPath + '/wh/pd/whPdStock/exportData',
      params: getForm().getFieldsValue(),
    });
  }
  onMounted(async () => {
    setProps();
    handleCompany();
  });

  async function handleCompany() {
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
    reload();
    await getForm().setFieldsValue({
      companyCode: userStore.getProjecte.code,
    });
  }
</script>
